package com.kfm.service;

import javax.swing.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Aurora雪
 */
public class ServiceCheck {
    /**
     * 服务器列表会放到一个`server.txt`文件中，请从`server.txt`文件中读取到服务器列表并
     * 发送`http`请求确定服务器上的接收文件服务是否正常，并在控制台显示检测结果
     */
    //格式化输出常量
    private static final int COLUMN_WIDTH3 = 22;
    private static final int COLUMN_WIDTH2 = 28;
    private static final int COLUMN_WIDTH = 20;
    private static final int COLUMN_WIDTH4 = 12;
    private static String line;
    static String serverAddress = null;

    static long startTime = 0L;
    static int statusCode = 0;
    private static JComboBox<Object> outputTextArea;

    public static void main(String[] args) {
        selectFile();
    }
    //选择要执行的文件
    public static void selectFile(){
        System.out.println("******************************");
        System.out.println("\u001B[36m 请选择要执行的文件：\u001B[0m");
        System.out.println("\u001B[36m 1.执行自带的文件 \u001B[0m");
        System.out.println("\u001B[36m 2.执行自己的文件 \u001B[0m");
        System.out.println("******************************");
        int menu = new Scanner(System.in).nextInt();
        switch (menu){
            case 1:
                start();
                break;
            case 2:
                System.out.println("请输入文件路径：");
                String path = new Scanner(System.in).nextLine();
                start(path);
                break;
            default:
                System.out.println("\u001B[33m 输入错误，请重新输入！\u001B[0m");
                selectFile();
                break;
        }
    }
    public static void start() {
        System.out.printf("%-" + COLUMN_WIDTH + "s", "当前线程名称");
        System.out.printf("%-" + COLUMN_WIDTH2 + "s", "服务器地址");
        System.out.printf("%-" + COLUMN_WIDTH3 + "s", "当前时间");
        System.out.printf("%-" + COLUMN_WIDTH4 + "s", "状态码");
        System.out.printf("%-" + COLUMN_WIDTH + "s", "服务器状态");
        System.out.println();

        // 相对路径
        String relativePath = "server.txt";

        // 获取当前工作目录
        String currentDir = System.getProperty("user.dir");

        // 获取相对路径的绝对路径
        Path absolutePath = Paths.get(currentDir,relativePath).normalize();

//        System.out.println(absolutePath);

        File file = new File(absolutePath.toUri());

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            //当前时间
            startTime = System.currentTimeMillis();
            System.out.println("开始时间：" + LocalTime.now());
            while ((serverAddress = reader.readLine()) != null) {
                checkServer(serverAddress);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void start(String path) {
        System.out.printf("%-" + COLUMN_WIDTH + "s", "当前线程名称");
        System.out.printf("%-" + COLUMN_WIDTH2 + "s", "服务器地址");
        System.out.printf("%-" + COLUMN_WIDTH3 + "s", "当前时间");
        System.out.printf("%-" + COLUMN_WIDTH4 + "s", "状态码");
        System.out.printf("%-" + COLUMN_WIDTH + "s", "服务器状态");
        System.out.println();

        String relativePath = path;

        File file = new File(relativePath);

        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            //当前时间
            startTime = System.currentTimeMillis();
            System.out.println("开始时间：" + LocalTime.now());
            while ((serverAddress = reader.readLine()) != null) {
                checkServer(serverAddress);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //创建线程池
    private static void checkServer(String serverAddress) {
        //创建一个固定大小为10的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while (true){
                    //调用
                    DetectionService(serverAddress);
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
    }

    //检测服务器
    private static void DetectionService(String serverAddress){
        try {
            URI uri = new URI(serverAddress);

            HttpClient httpClient = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(uri)
                    .GET()
                    .build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            statusCode = response.statusCode();
            Calendar calendar = Calendar.getInstance();
            Date time = calendar.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss");
            String formatTime = sdf.format(time);
            if(statusCode >= 200 && statusCode < 300){
                System.out.println(String.format("%-20s\t%-30s\t%-26s\t%-5d\t\t服务器状态正常", Thread.currentThread().getName(), serverAddress, formatTime, statusCode));
            } else if (statusCode >= 400 && statusCode < 500) {
                System.out.println(String.format("\u001B[33m %-20s\t%-30s\t%-26s\t%-5d\t\t服务器请求资源异常 \u001B[0m", Thread.currentThread().getName(), serverAddress, formatTime, statusCode));
            } else if(statusCode > 500){
                System.out.println(String.format("%-20s\t%-30s\t%-26s\t%-5d\t\t服务器状态错误", Thread.currentThread().getName(), serverAddress, formatTime, statusCode));
            }

        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {

//            System.out.println("┆执行时间：" + LocalTime.now() + "，┆服务器：" + serverAddress + " 访问异常，┆状态码: 连接超时");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}